<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 用户角色的列表数据 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="lev1class(i1)">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag effect="dark" closable @close="onTagClose(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 循环渲染二级权限 -->
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="lev2class(i2)">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag effect="dark" type="success" closable @close="onTagClose(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag effect="dark" v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="onTagClose(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="onSetRightDialogClose">
      <!-- 树形控件 -->
      <el-tree :data="rightslist" :props="treeProp" show-checkbox default-expand-all node-key="id" :default-checked-keys="defaultCheckedKeys" ref="treeRef"></el-tree>
      <!-- 底部的按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolelist: [],
      setRightDialogVisible: false,
      // 树形结构的权限数据
      rightslist: [],
      // 树形控件的属性配置对象
      treeProp: {
        label: 'authName',
        children: 'children'
      },
      // 树形控件默认被选中的节点的 Id 值的数组
      defaultCheckedKeys: [],
      // 当前角色的Id
      roleId: ''
    }
  },
  created() {
    this.getRolelist()
  },
  methods: {
    async getRolelist() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表数据失败！')
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 一级权限的样式
    lev1class(index) {
      return ['v-center', 'bd-bottom', index === 0 ? 'bd-top' : '']
    },
    // 二级权限的样式
    lev2class(index) {
      return ['v-center', index === 0 ? '' : 'bd-top']
    },
    // 响应 tag 标签的 close 事件
    async onTagClose(role, rightId) {
      // 询问用户是否要删除当前权限
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') return

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败！')

      // 把服务器响应的最新的权限，赋值给当前角色的 children 属性即可
      role.children = res.data
    },
    // 点击按钮，展示分配权限的对话框
    async showSetRightsDialog(role) {
      // 把当前角色的Id保存到 data 中，供其他函数使用
      this.roleId = role.id

      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败！')

      this.rightslist = res.data

      this.getLeafKeys(role, this.defaultCheckedKeys)

      // 展示对话框
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取到所有三级权限的Id，存放到数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(subNode => this.getLeafKeys(subNode, arr))
    },
    // 监听分配权限对话框的关闭事件
    onSetRightDialogClose() {
      this.defaultCheckedKeys = []
      this.roleId = ''
    },
    // 分配权限
    async allotRights() {
      // 得到所有全选和半选节点的Id，形成一个数组
      const ids = [
        // 全选节点的Id数组
        ...this.$refs.treeRef.getCheckedKeys(),
        // 半选节点的Id数组
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      // 调用接口，为角色分配权限
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: ids.join(',')
      })

      if (res.meta.status !== 200) return this.$message.error('分配权限失败！')
      this.$message.success('分配权限成功！')
      this.getRolelist()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 5px;
}

.bd-top {
  border-top: 1px solid #efefef;
}
.bd-bottom {
  border-bottom: 1px solid #efefef;
}

.v-center {
  display: flex;
  align-items: center;
}
</style>